package com.gepengjun.lims.config.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.gepengjun.lims.util.JsonResult.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShiroLoginFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest req, ServletResponse res) throws Exception {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String requestWith = request.getHeader("X-Requested-With");
        if (StringUtils.isNotEmpty(requestWith) && StringUtils.equals("XMLHttpRequest",requestWith)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(JSON.toJSONString(ResultUtil.error(-2,"还未登录,请登录")));
            return false;
        }
        return super.onAccessDenied(request, response);
    }
}
